package com.unlcn.ils.sales.backend.security;


import cn.huiyunche.commons.utils.AppUtil;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.sales.backend.security.domains.UserSecurityVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功需要向前台返回jwt.
 *
 * @author qichao
 */
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String secureKey = null;

    public JwtAuthenticationSuccessHandler(String secureKey) {
        this.secureKey = secureKey;
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserSecurityVO user = (UserSecurityVO) authentication.getPrincipal();
        String captcha = request.getParameter("captcha");
        String token = JwtUtils.generateToken(user, this.getSecureKey());
        JSONObject jsonObject = AppUtil.generateSuccessJson();
        jsonObject.put(JwtAuthenicationFilter.HEADER_AUTHORIZATION, JwtAuthenicationFilter.PREFIX_AUTHORIZATION + token);

        AppUtil.responseJson(response, jsonObject);
    }

    public void setSecureKey(String secureKey) {
        this.secureKey = secureKey;
    }

    private String getSecureKey() {
        return this.secureKey;
    }
}
